<template>
  <t-card>
    <t-space direction="vertical" style="width: 100%">
      <t-form
        v-show="showSearch"
        ref="queryRef"
        :data="queryParams"
        layout="inline"
        reset-type="initial"
        label-width="calc(4em + 12px)"
        label-align="top"
      >
        <t-form-item label="编号" name="enterpriseId">
          <t-input v-model="queryParams.enterpriseId" placeholder="请输入编号" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="企业名称" name="enterpriseName">
          <t-input v-model="queryParams.enterpriseName" placeholder="请输入企业名称" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label="会场" name="venues">
          <t-select
            v-model="queryParams.venuesId"
            clearable
            placeholder="请选择会场"
            :scroll="{ type: 'virtual' }"
            :popup-props="{ overlayInnerStyle: { height: '150px', width: '500px' } }"
            auto-width
          >
            <template #prefixIcon>
              <browse-icon style="margin-right: 8px" />
            </template>
            <template #panelTopContent>
              <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                <t-textarea v-model="xhljVenuesSearch" placeholder="请输入关键词搜索" @change="onSearchXhljVenues" />
              </div>
            </template>
            <t-option
              v-for="item in xhljVenuesOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="大会" name="conferenceInfo">
          <t-select
            v-model="queryParams.conferenceInfoId"
            clearable
            placeholder="请选择大会"
            :scroll="{ type: 'virtual' }"
            :popup-props="{ overlayInnerStyle: { height: '150px', width: '500px' } }"
            auto-width
          >
            <template #prefixIcon>
              <browse-icon style="margin-right: 8px" />
            </template>
            <template #panelTopContent>
              <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                <t-textarea
                  v-model="xhljConferenceInfoSearch"
                  placeholder="请输入关键词搜索"
                  @change="onSearchXhljConferenceInfo"
                />
              </div>
            </template>
            <t-option
              v-for="item in xhljConferenceInfoOptions"
              :key="item.value"
              :value="item.value"
              :label="item.label"
            ></t-option>
          </t-select>
        </t-form-item>
        <t-form-item label="企业介绍" name="backgroundContent">
          <t-input
            v-model="queryParams.backgroundContent"
            placeholder="请输入企业介绍"
            clearable
            @enter="handleQuery"
          />
        </t-form-item>
        <t-form-item label="联系电话" name="contactPhone">
          <t-input v-model="queryParams.contactPhone" placeholder="请输入联系电话" clearable @enter="handleQuery" />
        </t-form-item>
        <t-form-item label-width="0px">
          <t-space align="end" style="height: 64px">
            <t-button theme="primary" @click="handleQuery">
              <template #icon> <search-icon /></template>
              搜索
            </t-button>
            <t-button theme="default" @click="resetQuery">
              <template #icon> <refresh-icon /></template>
              重置
            </t-button>
          </t-space>
        </t-form-item>
      </t-form>

      <t-table
        v-model:column-controller-visible="columnControllerVisible"
        :loading="loading"
        hover
        row-key="enterpriseId"
        :data="enterpriseList"
        :columns="columns"
        :selected-row-keys="ids"
        select-on-row-click
        :pagination="pagination"
        :column-controller="{
          hideTriggerButton: true,
        }"
        :sort="sort"
        show-sort-column-bg-color
        @sort-change="handleSortChange"
        @select-change="handleSelectionChange"
      >
        <template #topContent>
          <t-row>
            <t-col flex="auto">
              <t-button v-hasPermi="['xhlj:enterprise:add']" theme="primary" @click="handleAdd">
                <template #icon> <add-icon /></template>
                新增
              </t-button>
              <t-button
                v-hasPermi="['xhlj:enterprise:edit']"
                theme="default"
                variant="outline"
                :disabled="single"
                @click="handleUpdate()"
              >
                <template #icon> <edit-icon /> </template>
                修改
              </t-button>
              <t-button
                v-hasPermi="['xhlj:enterprise:remove']"
                theme="danger"
                variant="outline"
                :disabled="multiple"
                @click="handleDelete()"
              >
                <template #icon> <delete-icon /> </template>
                删除
              </t-button>
              <t-button v-hasPermi="['xhlj:enterprise:export']" theme="default" variant="outline" @click="handleExport">
                <template #icon> <download-icon /> </template>
                导出
              </t-button>
              <span class="selected-count">已选 {{ ids.length }} 项</span>
            </t-col>
            <t-col flex="none">
              <t-button theme="default" shape="square" variant="outline" @click="showSearch = !showSearch">
                <template #icon> <search-icon /> </template>
              </t-button>
              <t-button theme="default" variant="outline" @click="columnControllerVisible = true">
                <template #icon> <setting-icon /> </template>
                列配置
              </t-button>
            </t-col>
          </t-row>
        </template>

        <!-- 单独列项配置 -->
        <template #venues="{ row }">
          <span v-if="row.venues && Object.keys(row.venues).length > 1">
            {{ row.venues[Object.keys(row.venues)[1]] }}（编号为{{ row.venues[Object.keys(row.venues)[0]] }}）
          </span>
        </template>

        <template #conferenceInfo="{ row }">
          <span v-if="row.conferenceInfo && Object.keys(row.conferenceInfo).length > 1">
            {{ row.conferenceInfo[Object.keys(row.conferenceInfo)[1]] }}（编号为{{
              row.conferenceInfo[Object.keys(row.conferenceInfo)[0]]
            }}）
          </span>
        </template>

        <template #sysUser="{ row }">
          <span v-if="row.sysUser && Object.keys(row.sysUser).length > 1">
            {{ row.sysUser[Object.keys(row.sysUser)[1]] }}（编号为{{ row.sysUser[Object.keys(row.sysUser)[0]] }}）
          </span>
        </template>

        <template #enterpriseVideoImage="{ row }">
          <image-preview :src="row.enterpriseVideoImage" :width="60" :height="60" />
        </template>

        <template #enterpriseFile="{ row }">
          <t-tooltip
            v-for="(url, index) in row.enterpriseFile.split(',')"
            v-if="row.enterpriseFile"
            :key="index"
            :content="getUrlFileName(url)"
            destroy-on-close
            show-arrow
            placement="top-left"
            theme="light"
          >
            <t-link
              :href="url"
              class="custom-link"
              theme="primary"
              target="_blank"
              @click.prevent="previewOrRedirect(url)"
            >
              {{ getUrlFileName(url) }}
            </t-link>
          </t-tooltip>
        </template>

        <template #enterpriseMap="{ row }">
          <t-button @click.stop="openDialog(row.enterpriseMap)">显示地图</t-button>
        </template>

        <template #finishImage="{ row }">
          <image-preview :src="row.finishImage" :width="60" :height="60" />
        </template>

        <template #operation="{ row }">
          <t-space :size="8" break-line>
            <t-link
              v-hasPermi="['xhlj:enterprise:query']"
              theme="primary"
              hover="color"
              @click.stop="handleDetail(row)"
            >
              <browse-icon />详情
            </t-link>
            <t-link v-hasPermi="['xhlj:enterprise:edit']" theme="primary" hover="color" @click.stop="handleUpdate(row)">
              <edit-icon />修改
            </t-link>
            <t-link
              v-hasPermi="['xhlj:enterprise:remove']"
              theme="danger"
              hover="color"
              @click.stop="handleDelete(row)"
            >
              <delete-icon />删除
            </t-link>
          </t-space>
        </template>
      </t-table>
    </t-space>
    <!-- 添加或修改企业展商对话框 -->
    <t-dialog
      v-model:visible="open"
      :header="title"
      destroy-on-close
      :close-on-overlay-click="false"
      width="1100px"
      attach="body"
      :confirm-btn="{
        loading: buttonLoading,
      }"
      @confirm="onConfirm"
    >
      <t-loading :loading="buttonLoading">
        <t-form
          ref="enterpriseRef"
          label-align="top"
          :data="form"
          :rules="rules"
          label-width="calc(5em + 41px)"
          scroll-to-first-error="smooth"
          layout="inline"
          @submit="submitForm"
        >
          <t-form-item label="企业名称" name="enterpriseName" style="width: 90%">
            <t-textarea
              v-model="form.enterpriseName"
              placeholder="请输入企业名称"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="会场" name="venues" style="width: 100%">
            <t-select
              v-model="form.venuesId"
              clearable
              placeholder="请选择会场"
              :scroll="{ type: 'virtual' }"
              :popup-props="{ overlayInnerStyle: { height: '150px', width: '500px' } }"
              auto-width
            >
              <template #prefixIcon>
                <browse-icon style="margin-right: 8px" />
              </template>
              <template #panelTopContent>
                <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                  <t-textarea v-model="xhljVenuesSearch" placeholder="请输入关键词搜索" @change="onSearchXhljVenues" />
                </div>
              </template>
              <t-option
                v-for="item in xhljVenuesOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></t-option>
            </t-select>
          </t-form-item>

          <t-form-item label="大会" name="conferenceInfo" style="width: 100%">
            <t-select
              v-model="form.conferenceInfoId"
              clearable
              placeholder="请选择大会"
              :scroll="{ type: 'virtual' }"
              :popup-props="{ overlayInnerStyle: { height: '150px', width: '500px' } }"
              auto-width
            >
              <template #prefixIcon>
                <browse-icon style="margin-right: 8px" />
              </template>
              <template #panelTopContent>
                <div :style="{ position: 'sticky', top: '0', zIndex: 1 }">
                  <t-textarea
                    v-model="xhljConferenceInfoSearch"
                    placeholder="请输入关键词搜索"
                    @change="onSearchXhljConferenceInfo"
                  />
                </div>
              </template>
              <t-option
                v-for="item in xhljConferenceInfoOptions"
                :key="item.value"
                :value="item.value"
                :label="item.label"
              ></t-option>
            </t-select>
          </t-form-item>

          <t-form-item label="企业介绍" name="backgroundContent">
            <editor v-model="form.backgroundContent" />
          </t-form-item>

          <t-form-item label="展商风采展示图" name="enterpriseVideoImage" style="width: 100%">
            <image-upload v-model="form.enterpriseVideoImage" :limit="0" />
          </t-form-item>

          <t-form-item label="展商视频" name="enterpriseFile" style="width: 100%">
            <file-upload v-model="form.enterpriseFile" :limit="0" />
          </t-form-item>

          <t-form-item label="营业执照号" name="businessLicenseNumber" style="width: 90%">
            <t-textarea
              v-model="form.businessLicenseNumber"
              placeholder="请输入营业执照号"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="成立日期" name="establishmentDate">
            <t-date-picker
              v-model="form.establishmentDate"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择成立日期"
            />
          </t-form-item>

          <t-form-item label="展商地址地图" name="enterpriseMap" style="width: 90%">
            <t-textarea
              v-model="form.enterpriseMap"
              placeholder="请输入展商地址地图"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="展商开始时间" name="startTime">
            <t-date-picker
              v-model="form.startTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择展商开始时间"
            />
          </t-form-item>

          <t-form-item label="展商结束时间" name="endTime">
            <t-date-picker
              v-model="form.endTime"
              enable-time-picker
              allow-input
              clearable
              placeholder="请选择展商结束时间"
            />
          </t-form-item>

          <t-form-item label="展商地址" name="enterpriseLocation" style="width: 90%">
            <t-textarea
              v-model="form.enterpriseLocation"
              placeholder="请输入展商地址"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="联系人（多个联系人用逗号分割）" name="contactPersons" style="width: 90%">
            <t-textarea
              v-model="form.contactPersons"
              placeholder="请输入联系人（多个联系人用逗号分割）"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="联系电话" name="contactPhone" style="width: 90%">
            <t-textarea
              v-model="form.contactPhone"
              placeholder="请输入联系电话"
              name="description"
              :autosize="{ minRows: 3, maxRows: 6 }"
            />
          </t-form-item>

          <t-form-item label="打卡二维码" name="finishImage" style="width: 100%">
            <image-upload v-model="form.finishImage" :limit="0" />
          </t-form-item>
        </t-form>
      </t-loading>
    </t-dialog>

    <!-- 办公文件预览 -->
    <t-dialog
      :visible="localOfficeFileProviewVisible"
      title="文档预览"
      width="70%"
      style="position: absolute"
      :close-btn="false"
      close-on-esc-keydown
      :footer="false"
      show-overlay
      placement="center"
      @close="updateOfficeFileProviewVisible(false)"
    >
      <template #default>
        <t-link :href="file" theme="primary" hover="color"><t-button>下载文件</t-button></t-link>
        <!-- 动态选择预览组件 -->
        <component :is="fileTypeComponents[fileType]" v-if="fileType && fileTypeComponents[fileType]" :src="file" />
        <!-- 如果文件类型不被支持 -->
        <div v-else>该文件类型不支持预览。</div>
      </template>
    </t-dialog>
    <!-- 地图 -->
    <t-dialog
      :visible="mapDialogVisible"
      title="地图显示"
      width="70%"
      style="position: absolute"
      :close-btn="false"
      close-on-esc-keydown
      :footer="false"
      show-overlay
      placement="center"
      @close="handleClose"
    >
      <template #default>
        <div id="map" style="height: 400px"></div>
      </template>
    </t-dialog>
    <!-- 企业展商详情 -->
    <t-dialog
      v-model:visible="openView"
      header="企业展商详情"
      placement="center"
      width="800px"
      attach="body"
      :footer="false"
    >
      <my-descriptions :loading="openViewLoading">
        <t-descriptions-item label="编号">{{ form.enterpriseId }}</t-descriptions-item>

        <t-descriptions-item label="企业名称" :span="2">{{ form.enterpriseName }}</t-descriptions-item>

        <span v-if="form.venues && Object.keys(form.venues).length > 1">
          {{ form.venues[Object.keys(form.venues)[1]] }}（编号为{{ form.venues[Object.keys(form.venues)[0]] }}）
        </span>

        <span v-if="form.conferenceInfo && Object.keys(form.conferenceInfo).length > 1">
          {{ form.conferenceInfo[Object.keys(form.conferenceInfo)[1]] }}（编号为{{
            form.conferenceInfo[Object.keys(form.conferenceInfo)[0]]
          }}）
        </span>

        <span v-if="form.sysUser && Object.keys(form.sysUser).length > 1">
          {{ form.sysUser[Object.keys(form.sysUser)[1]] }}（编号为{{ form.sysUser[Object.keys(form.sysUser)[0]] }}）
        </span>

        <t-descriptions-item label="企业介绍" :span="2">
          <editor-preview :html-text="form.backgroundContent" />
        </t-descriptions-item>

        <t-descriptions-item label="展商风采展示图">
          <image-preview :src="form.enterpriseVideoImage" :width="60" :height="60" />
        </t-descriptions-item>

        <t-descriptions-item label="展商视频">{{ form.enterpriseFile }}</t-descriptions-item>

        <t-descriptions-item label="营业执照号" :span="2">{{ form.businessLicenseNumber }}</t-descriptions-item>

        <t-descriptions-item label="成立日期">{{ parseTime(form.establishmentDate) }}</t-descriptions-item>

        <t-descriptions-item label="展商地址地图">{{ form.enterpriseMap }}</t-descriptions-item>

        <t-descriptions-item label="展商开始时间">{{ parseTime(form.startTime) }}</t-descriptions-item>

        <t-descriptions-item label="展商结束时间">{{ parseTime(form.endTime) }}</t-descriptions-item>

        <t-descriptions-item label="展商地址" :span="2">{{ form.enterpriseLocation }}</t-descriptions-item>

        <t-descriptions-item label="联系人（多个联系人用逗号分割）" :span="2">{{
          form.contactPersons
        }}</t-descriptions-item>

        <t-descriptions-item label="联系电话" :span="2">{{ form.contactPhone }}</t-descriptions-item>

        <t-descriptions-item label="创建时间">{{ parseTime(form.createTime) }}</t-descriptions-item>

        <t-descriptions-item label="打卡二维码">
          <image-preview :src="form.finishImage" :width="60" :height="60" />
        </t-descriptions-item>
      </my-descriptions>
    </t-dialog>
  </t-card>
</template>

<script lang="tsx" setup>
defineOptions({
  name: 'Enterprise',
});
import '@vue-office/excel/lib/index.css';
import '@vue-office/docx/lib/index.css';

import AMapLoader from '@amap/amap-jsapi-loader';
import VueOfficeDocx from '@vue-office/docx';
import VueOfficeExcel from '@vue-office/excel';
// office文件预览
import VueOfficePdf from '@vue-office/pdf';
import {
  AddIcon,
  BookIcon,
  BrowseIcon,
  DeleteIcon,
  DownloadIcon,
  EditIcon,
  RefreshIcon,
  SearchIcon,
  SettingIcon,
} from 'tdesign-icons-vue-next';
import type {
  FormInstanceFunctions,
  FormRule,
  PageInfo,
  PrimaryTableCol,
  SelectProps,
  SubmitContext,
  TableSort,
  TextareaProps,
} from 'tdesign-vue-next';
import { computed, getCurrentInstance, ref } from 'vue';

import { listConferenceInfo } from '@/api/xhlj/conferenceInfo';
import { addEnterprise, delEnterprise, getEnterprise, listEnterprise, updateEnterprise } from '@/api/xhlj/enterprise';
import type { XhljConferenceInfoQuery } from '@/api/xhlj/model/conferenceInfo';
import type { XhljEnterpriseForm, XhljEnterpriseQuery, XhljEnterpriseVo } from '@/api/xhlj/model/enterpriseModel';
import type { XhljVenuesQuery } from '@/api/xhlj/model/venues';
import { listVenues } from '@/api/xhlj/venues';
import Editor from '@/components/editor/index.vue';
import EditorPreview from '@/components/editor-preview/index.vue';
// video预览
import Video from '@/components/video/index.vue';
import { ArrayOps } from '@/utils/array';

const { proxy } = getCurrentInstance();

const openView = ref(false);
const openViewLoading = ref(false);
const enterpriseRef = ref<FormInstanceFunctions>();
const open = ref(false);
const buttonLoading = ref(false);
const title = ref('');
const enterpriseList = ref<XhljEnterpriseVo[]>([]);
const loading = ref(false);
const columnControllerVisible = ref(false);
const showSearch = ref(true);
const total = ref(0);
const ids = ref([]);
const single = ref(true);
const multiple = ref(true);
const sort = ref<TableSort>();
const xhljVenuesQueryParams = ref<XhljVenuesQuery>({
  pageNum: 1,
  pageSize: 10000,
});
const xhljVenuesList = ref<SelectProps['options']>([]);
const xhljVenuesOptions = ref<SelectProps['options']>([]);
const xhljVenuesSearch = ref('');
const onSearchXhljVenues = () => {
  xhljVenuesOptions.value = xhljVenuesList.value
    .map((item) => ({
      label: item[Object.keys(item)[1]],
      value: item[Object.keys(item)[0]],
    }))
    .filter((option) => option.label.includes(xhljVenuesSearch.value));
};
/** 查询会场列表 */
async function getXhljVenuesList() {
  listVenues(xhljVenuesQueryParams.value).then((response) => {
    xhljVenuesList.value = response.rows;
    const labelValue = response.rows.map((item) => ({
      label: item[Object.keys(item)[1]],
      value: item[Object.keys(item)[0]],
    }));
    xhljVenuesOptions.value = labelValue;
    console.log('xhljVenuesList', xhljVenuesList.value);
    console.log('xhljVenuesOptions', xhljVenuesOptions);
  });
}

const xhljConferenceInfoQueryParams = ref<XhljConferenceInfoQuery>({
  pageNum: 1,
  pageSize: 10000,
});
const xhljConferenceInfoList = ref<SelectProps['options']>([]);
const xhljConferenceInfoOptions = ref<SelectProps['options']>([]);
const xhljConferenceInfoSearch = ref('');
const onSearchXhljConferenceInfo = () => {
  xhljConferenceInfoOptions.value = xhljConferenceInfoList.value
    .map((item) => ({
      label: item[Object.keys(item)[1]],
      value: item[Object.keys(item)[0]],
    }))
    .filter((option) => option.label.includes(xhljConferenceInfoSearch.value));
};
/** 查询大会列表 */
async function getXhljConferenceInfoList() {
  listConferenceInfo(xhljConferenceInfoQueryParams.value).then((response) => {
    xhljConferenceInfoList.value = response.rows;
    const labelValue = response.rows.map((item) => ({
      label: item[Object.keys(item)[1]],
      value: item[Object.keys(item)[0]],
    }));
    xhljConferenceInfoOptions.value = labelValue;
    console.log('xhljConferenceInfoList', xhljConferenceInfoList.value);
    console.log('xhljConferenceInfoOptions', xhljConferenceInfoOptions);
  });
}

// office预览
// 定义Props和Emits
const props = defineProps<{
  officeFileProviewVisible: boolean;
  officeFile?: string;
}>();
const emit = defineEmits(['update:officeFileProviewVisible']);
// 文件类型组件映射
const fileTypeComponents = {
  docx: VueOfficeDocx,
  xlsx: VueOfficeExcel,
  pdf: VueOfficePdf,
  mp4: Video,
} as const;
// 控制预览弹窗显示的本地状态
const localOfficeFileProviewVisible = ref(props.officeFileProviewVisible);
const file = ref(props.officeFile || '');
// 更新父组件的prop值
const updateOfficeFileProviewVisible = (value: boolean) => {
  localOfficeFileProviewVisible.value = value;
  emit('update:officeFileProviewVisible', value);
};
// 根据URL预览或跳转
const previewOrRedirect = (url: string) => {
  const extension = url.slice(((url.lastIndexOf('.') - 1) >>> 0) + 2).toLowerCase();
  if (fileTypeComponents[extension]) {
    file.value = url;
    updateOfficeFileProviewVisible(true);
  } else {
    window.open(url);
  }
};
// 从URL中获取文件名
const getUrlFileName = (url: string): string => url.substring(url.lastIndexOf('/') + 1);
// 计算文件类型
const fileType = computed(() => {
  return file.value ? file.value.slice(file.value.lastIndexOf('.') + 1).toLowerCase() : null;
});
const mapDialogVisible = ref(false);
const map = ref(null);
const marker = ref(null);
// 打开地图弹窗并加载地图
function openDialog(location: string) {
  const [longitude, latitude] = location.split(',').map(Number);
  mapDialogVisible.value = true;
  AMapLoader.load({
    key: 'a91a5c7609e42a3a3fdcc918ef1c7e94', // 替换成你的高德地图key
    plugins: ['AMap.Geomap'],
  })
    .then((AMap) => {
      map.value = new AMap.Map('map', {
        center: [longitude, latitude],
        zoom: 13,
      });
      marker.value = new AMap.Marker({
        position: [longitude, latitude],
        map: map.value,
      });
    })
    .catch((error) => {
      console.error('加载高德地图失败:', error);
    });
}
// 定义关闭对话框的方法
function handleClose() {
  mapDialogVisible.value = false;
}
// 校验规则
const rules = ref<Record<string, Array<FormRule>>>({});
// 列显隐信息
const columns = ref<Array<PrimaryTableCol>>([
  { title: `选择列`, colKey: 'row-select', type: 'multiple', width: 50, align: 'center', fixed: 'left' },
  { title: `编号`, colKey: 'enterpriseId', align: 'center', ellipsis: { theme: 'light' }, fixed: 'left' },
  { title: `企业名称`, colKey: 'enterpriseName', align: 'center', minWidth: 140, ellipsis: { theme: 'light' } },
  {
    title: `会场`,
    colKey: 'venues',
    align: 'center',
    minWidth: 155,
    ellipsis: { theme: 'light' },
    className: ({ row }) => {
      return 'custom-cell-class-name';
    },
    attrs: ({ row }) => {
      return {
        style: {
          color: '#fff', // 白色文字
          fontWeight: 'bold', // 字体加粗
          background: 'linear-gradient(to right, #4facfe 0%, #00f2fe 100%)', // 渐变背景
          transition: 'all 0.3s ease', // 添加过渡效果
          borderRadius: '4px', // 圆角
        },
      };
    },
  },
  {
    title: `大会`,
    colKey: 'conferenceInfo',
    align: 'center',
    minWidth: 155,
    ellipsis: { theme: 'light' },
    className: ({ row }) => {
      return 'custom-cell-class-name';
    },
    attrs: ({ row }) => {
      return {
        style: {
          color: '#fff', // 白色文字
          fontWeight: 'bold', // 字体加粗
          background: 'linear-gradient(to right, #4facfe 0%, #00f2fe 100%)', // 渐变背景
          transition: 'all 0.3s ease', // 添加过渡效果
          borderRadius: '4px', // 圆角
        },
      };
    },
  },
  { title: `系统用户`, colKey: 'sysUser', align: 'center', minWidth: 155, ellipsis: { theme: 'light' } },
  { title: `企业介绍`, colKey: 'backgroundContent', align: 'center', minWidth: 140, ellipsis: { theme: 'light' } },
  { title: `展商风采展示图`, colKey: 'enterpriseVideoImage', align: 'center', minWidth: 160 },
  { title: `展商视频`, colKey: 'enterpriseFile', align: 'center', minWidth: 180 },
  {
    title: `营业执照号`,
    colKey: 'businessLicenseNumber',
    align: 'center',
    minWidth: 140,
    ellipsis: { theme: 'light' },
  },
  { title: `成立日期`, colKey: 'establishmentDate', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `展商地址地图`, colKey: 'enterpriseMap', align: 'center', minWidth: 160 },
  { title: `展商开始时间`, colKey: 'startTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `展商结束时间`, colKey: 'endTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `展商地址`, colKey: 'enterpriseLocation', align: 'center', minWidth: 140, ellipsis: { theme: 'light' } },
  {
    title: `联系人（多个联系人用逗号分割）`,
    colKey: 'contactPersons',
    align: 'center',
    minWidth: 140,
    ellipsis: { theme: 'light' },
  },
  { title: `联系电话`, colKey: 'contactPhone', align: 'center', minWidth: 140, ellipsis: { theme: 'light' } },
  { title: `创建时间`, colKey: 'createTime', align: 'center', minWidth: 112, width: 120, sorter: true },
  { title: `打卡二维码`, colKey: 'finishImage', align: 'center', minWidth: 160 },
  { title: `操作`, colKey: 'operation', align: 'center', width: 120, fixed: 'right' },
]);
// 提交表单对象
const form = ref<XhljEnterpriseVo & XhljEnterpriseForm>({});
// 查询对象
const queryParams = ref<XhljEnterpriseQuery>({
  pageNum: 1,
  pageSize: 10,
  enterpriseId: undefined,
  enterpriseName: undefined,
  venues: undefined,
  conferenceInfo: undefined,
  sysUser: undefined,
  backgroundContent: undefined,
  industryTypes: undefined,
  achieveTags: undefined,
  contactPhone: undefined,
});
// 分页
const pagination = computed(() => {
  return {
    current: queryParams.value.pageNum,
    pageSize: queryParams.value.pageSize,
    total: total.value,
    showJumper: true,
    onChange: (pageInfo: PageInfo) => {
      queryParams.value.pageNum = pageInfo.current;
      queryParams.value.pageSize = pageInfo.pageSize;
      getList();
    },
  };
});

/** 查询企业展商列表 */
function getList() {
  loading.value = true;
  listEnterprise(queryParams.value)
    .then((response) => {
      enterpriseList.value = response.rows;
      total.value = response.total;
      console.log('Enterprise', response.rows);
    })
    .finally(() => (loading.value = false));
}

// 表单重置
function reset() {
  form.value = {};
  proxy.resetForm('enterpriseRef');
}

/** 搜索按钮操作 */
function handleQuery() {
  queryParams.value.pageNum = 1;
  getList();
}

/** 重置按钮操作 */
function resetQuery() {
  proxy.resetForm('queryRef');
  queryParams.value.pageNum = 1;
  handleSortChange(null);
}

/** 排序触发事件 */
function handleSortChange(value?: TableSort) {
  sort.value = value;
  if (Array.isArray(value)) {
    queryParams.value.orderByColumn = value.map((item) => item.sortBy).join(',');
    queryParams.value.isAsc = value.map((item) => (item.descending ? 'descending' : 'ascending')).join(',');
  } else {
    queryParams.value.orderByColumn = value?.sortBy;
    queryParams.value.isAsc = value?.descending ? 'descending' : 'ascending';
  }
  getList();
}

/** 多选框选中数据 */
function handleSelectionChange(selection: Array<string | number>) {
  ids.value = selection;
  single.value = selection.length !== 1;
  multiple.value = !selection.length;
}

/** 新增按钮操作 */
function handleAdd() {
  reset();
  open.value = true;
  title.value = '添加企业展商';
}

/** 详情按钮操作 */
function handleDetail(row: XhljEnterpriseVo) {
  reset();
  openView.value = true;
  openViewLoading.value = true;
  const enterpriseId = row.enterpriseId;
  getEnterprise(enterpriseId).then((response) => {
    form.value = response.data;
    openViewLoading.value = false;
  });
}

/** 修改按钮操作 */
function handleUpdate(row?: XhljEnterpriseVo) {
  buttonLoading.value = true;
  reset();
  open.value = true;
  title.value = '修改企业展商';
  const enterpriseId = row?.enterpriseId || ids.value.at(0);
  getEnterprise(enterpriseId).then((response) => {
    buttonLoading.value = false;
    form.value = response.data;
  });
}

/** 提交按钮 */
function onConfirm() {
  enterpriseRef.value.submit();
}

/** 提交表单 */
function submitForm({ validateResult, firstError }: SubmitContext) {
  if (validateResult === true) {
    buttonLoading.value = true;
    const msgLoading = proxy.$modal.msgLoading('提交中...');
    if (form.value.enterpriseId) {
      updateEnterprise(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('修改成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    } else {
      addEnterprise(form.value)
        .then(() => {
          proxy.$modal.msgSuccess('新增成功');
          open.value = false;
          getList();
        })
        .finally(() => {
          buttonLoading.value = false;
          proxy.$modal.msgClose(msgLoading);
        });
    }
  } else {
    proxy.$modal.msgError(firstError);
  }
}

/** 删除按钮操作 */
function handleDelete(row?: XhljEnterpriseVo) {
  const enterpriseIds = row?.enterpriseId || ids.value;
  proxy.$modal.confirm(`是否确认删除企业展商编号为${enterpriseIds}的数据项？`, () => {
    const msgLoading = proxy.$modal.msgLoading('正在删除中...');
    return delEnterprise(enterpriseIds)
      .then(() => {
        ids.value = ArrayOps.fastDeleteElement(ids.value, enterpriseIds);
        getList();
        proxy.$modal.msgSuccess('删除成功');
      })
      .finally(() => {
        proxy.$modal.msgClose(msgLoading);
      });
  });
}

/** 导出按钮操作 */
function handleExport() {
  proxy.download(
    'xhlj/enterprise/export',
    {
      ...queryParams.value,
    },
    `enterprise_${new Date().getTime()}.xlsx`,
  );
}

onMounted(() => {
  getXhljVenuesList();
  getXhljConferenceInfoList();
  getList();
});
</script>
<style>
.t-table td.custom-cell-class-name {
  font-size: 16px;
  padding: 10px;
  text-shadow: none;
  transition:
    transform 0.3s ease,
    text-shadow 0.3s ease;
}
.t-table td.custom-cell-class-name:hover {
  transform: scale(1.05); /* 缩放动画 */
  text-shadow: 0 0 4px rgba(0, 0, 0, 0.5); /* 文字阴影动画 */
  background: linear-gradient(to right, #00f2fe 0%, #4facfe 100%); /* 悬停时背景色渐变方向反转 */
}
.custom-link {
  display: inline-flex;
  align-items: center;
  gap: 8px;
  background: linear-gradient(to right, #007bff, #0056b3);
  color: white;
  padding: 8px 16px;
  margin-top: 5px;
  border-radius: 20px;
  text-decoration: none;
  box-shadow: 0 4px 6px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease-in-out;
}
.custom-link:hover {
  background: linear-gradient(to right, #0056b3, #007bff);
  transform: translateY(-2px) scale(1.03);
  box-shadow: 0 6px 8px rgba(0, 0, 0, 0.2);
}
</style>
